package com.github.cakin.shiro.chapter6.service;

import com.github.cakin.shiro.chapter6.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * @className: PasswordHelper
 * @description: 密码工具类
 * @date: 2020/5/19
 * @author: cakin
 */
public class PasswordHelper {
    /**
     * 伪随机数生成器
     */
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    /**
     * hash 算法定义
     */
    private String algorithmName = "md5";
    /**
     * 迭代次数
     */
    private final int hashIterations = 2;
    /**
     * 功能描述：加密用户的密码
     *
     * @author cakin
     * @date 2020/5/19
     * @param user 用户
     */
    public void encryptPassword(User user) {
        // 设置盐
        user.setSalt(randomNumberGenerator.nextBytes().toHex());
        // 得到密文
        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
}
